﻿

//基本的逻辑运算
function If(){
	this.isCal = true;
	//this.exception = common.ObjectFactory.getInstance().getException();
}

If.prototype = {
	calculate:function(expression){
		var expressionArr = expression.split(",");
		if(expressionArr.length>3){
			this.exception.doException("if函数的参数超过3个");
		}
		if(expressionArr.length==1){//需要将 = 变为 == ，将字符串加''
			var expression2 = "";
			var leftExp = "";//符号的左边
			for(var i=0;i<expression.length;i++){
				var c = expression.charAt(i);
				if(CalculateUtil.isLogic(c) && leftExp.trim()!=""){
					//alert("leftExp = " + leftExp);
					var nextC = expression.charAt(i+1);
					expression2 = this.addQuotes(leftExp,expression2);
					leftExp = "";
					expression2 += c;
					if(c=='=' && nextC!='='){
						expression2 += '=';
					}
					if(CalculateUtil.isLogic(nextC)){
						expression2 += nextC;
						i++;
					}
					var rightExp = "";//符号的右边
					var j=i+1;
					for(;j<expression.length;j++){
						var rightC = expression.charAt(j);
						if(CalculateUtil.isLogic(rightC)){
							expression2 = this.addQuotes(rightExp,expression2);
							break;
						}else{
							rightExp += rightC;
						}
					}
					if(j==expression.length){
						expression2 = this.addQuotes(rightExp,expression2);
					}
					i = j-1;
					//alert("rightExp = " + rightExp);
				}else{
					if(CalculateUtil.isLogic(c)) expression2 += c;
					else leftExp += c;
				}
			}
			return eval(expression2);
		}
		else if(expressionArr.length>=2){
			var ifExpression = expressionArr[0];
			var flag = eval(ifExpression);
			if(flag) return eval(expressionArr[1]);
			else if(expressionArr.length>=3) return eval(expressionArr[2]);
			else return null;
		}
		return null;
	},
	//对字符串添加单引号
	addQuotes:function(varExp,expression2){
		if(!CalculateUtil.isNumberAndPoint(varExp.trim()) && varExp.charAt(0)!="'"){
			expression2 += "'" + varExp.trim() + "'";
		}else{
			expression2 += varExp.trim();
		}
		return expression2;
	}
}